// import WebSocket from "ws";
import { client, connection } from "websocket";
export class Sync {
  private dataArr: {
    componentId: string;
    componentName: string;
  }[] = [];
  private websocket = new client();
  private connection: null | connection = null;
  constructor() {
    // "ws://127.0.0.1:8080"
    this.websocket.connect(`ws://${location.hostname}:8080`);
    this.websocket.on("connect", (con) => {
      this.connection = con;
    });
  }
  public syncComponent(componentId: string, componentName: string) {
    this.dataArr.push({
      componentId,
      componentName,
    });
  }

  public sync() {
    // this.webSocket.send("com");
    if (this.connection === null) {
      console.log("connection is null", this.dataArr);
      setTimeout(() => {
        this.sync();
      }, 3000);
      return;
    }
    this.connection.send(
      JSON.stringify({
        from: "user",
        to: "server",
        msg: "sync|" + JSON.stringify(this.dataArr),
      })
    );
  }
}
